package org.feng.resource;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Iterator;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.feng.entity.Device;
import org.feng.entity.EntityPool;
import org.feng.entity.Orders;
import org.feng.entity.ServiceProvider;
import org.feng.entity.User;
import org.jboss.logging.Logger;

import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.panache.common.Sort;
import io.quarkus.security.identity.SecurityIdentity;
import io.vertx.ext.web.Locale;

@Path("/orders")
@Produces(MediaType.APPLICATION_JSON)
//@Consumes(MediaType.APPLICATION_JSON)
public class OrdersRs {

	private static final Logger LOG = Logger.getLogger(DeviceRs.class);
	
	public OrdersRs() {
	}
	// 认证对象,可以获取已经认证通过的用户信息
	@Inject
	SecurityIdentity si;
	
	/**
	 * 查询订单
	 * 
	 * @throws ParseException
	 */
	 //@Path("/list")
	@GET
	public RetMsg list(@QueryParam("svrId") String svrId, @QueryParam("type") String type,
			@QueryParam("deviceId") String deviceId, @QueryParam("payStatus") String payStatus,
			@QueryParam("startDate") String startDate, @QueryParam("endDate") String endDate,
			@QueryParam("selectDate") Integer selectDate, @QueryParam("page") Integer pageIndex,
			@QueryParam("limit") Integer pageSize) throws ParseException {
		// DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 设定格式
		dateFormat.setLenient(false);
		// java.sql.Timestamp dateTime = new
		// java.sql.Timestamp(timeDate.getTime());//Timestamp类型,timeDate.getTime()返回一个long型

		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		User us = (User) si.getAttribute("userInfo");
		String sqlWhere = "ispId=" + us.ispId;// 把标记为删除的数据滤掉
		if (us.type == 1) {// 限制只访问自己的数据,只有平台可以访问所有的
			sqlWhere += " and svrId = " + us.svrId;
		} else {
			if (null != svrId && (!"".equals(svrId)))
				sqlWhere += " and svrId=" + svrId;
		}
		if ("".equals(startDate)) {
			startDate=null;
		}
		if ("".equals(endDate)) {
			endDate=null;
		}
		// LOG.info("Device:id "+id);
		if (null != type && (!"".equals(type)))
			sqlWhere += " and type=" + type;
		// if (null!=position && (!"".equals(position)))
		// sqlWhere += " and position like '%" + position + "%'";
		if (null != deviceId && (!"".equals(deviceId)))
			sqlWhere += " and deviceId = " + deviceId;
		if (null != payStatus && (!"".equals(payStatus)))
			sqlWhere += " and payStatus=" + payStatus;

		PanacheQuery<Orders> pageSp = null;
		if (selectDate!=null&& selectDate> 0) {
			sqlWhere += "  and modifyTime>=?1";
			LocalDateTime startDateT = LocalDateTime.now(); // 2019-01-31
			startDateT = startDateT.minus(selectDate, ChronoUnit.MINUTES);
			//LOG.info("Device:selectDate=" + selectDate);
			//LOG.info("Device:startDateT=" + startDateT.toString());
			Date stDate=Date.from( startDateT.atZone( ZoneId.systemDefault()).toInstant());
			pageSp = Orders.find(sqlWhere, stDate);// 按id倒排序
		} else if (null != startDate && null != endDate) {
			sqlWhere += " and modifyTime>=?1  and modifyTime<?2";
			//LOG.info("Device: startDate=" + startDate);
			//LOG.info("Device: endDate=" + endDate);
			Date startDateT = dateFormat.parse(startDate);// util类型
			Date endDateT = dateFormat.parse(endDate);// util类型
			pageSp = Orders.find(sqlWhere, startDateT, endDateT);// 按id倒排序
		} else if (null != startDate) {// 时间处理很麻烦
			sqlWhere += " and modifyTime>=?1";
			Date startDateT = dateFormat.parse(startDate);// util类型
			pageSp = Orders.find(sqlWhere, startDateT);// 按id倒排序
		} else if (null != endDate) {// 时间处理很麻烦
			sqlWhere += " and modifyTime<?1";
			Date endDateT = dateFormat.parse(endDate);// util类型
			pageSp = Orders.find(sqlWhere, endDateT);// 按id倒排序
		} else {
			pageSp = Orders.find(sqlWhere, Sort.ascending("id"));
		}

		LOG.info("Device:" + sqlWhere);
		// pageSp = Orders.find(sqlWhere,Sort.ascending("id"));//按id倒排序
		if (pageIndex==null||pageIndex < 1)
			pageIndex = 1;
		if (pageSize==null|| pageSize< 1)
			pageSize = 20;
		pageSp.page(pageIndex - 1, pageSize);// pageIndex 在页面从1开始,但后台从0开始
		rm.data = pageSp.list();
		rm.count = pageSp.count();
		return rm;
	}

	/**
	 * 查询openId用户订单,不需要认证,小程序查询历史用
	 */
	@Path("openid/{openid}")
	@GET
	public RetMsg user(@PathParam("openid") String openid, @QueryParam("startDate") String startDate,
			@QueryParam("endDate") String endDate, @QueryParam("page") int pageIndex,
			@QueryParam("limit") int pageSize) {
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		String sqlWhere = "openId ='" + openid + "'";
		if (null != startDate && (!"".equals(startDate)))
			sqlWhere += " and startDate>='" + startDate + "'";
		if (null != endDate && (!"".equals(endDate)))
			sqlWhere += " and endDate>='" + endDate + "'";
		PanacheQuery<Orders> pageSp = Orders.find(sqlWhere, Sort.ascending("id"));// 按id倒排序
		if (pageIndex < 1)
			pageIndex = 1;
		if (pageSize < 1)
			pageSize = 20;
		pageSp.page(pageIndex - 1, pageSize);// pageIndex 在页面从1开始,但后台从0开始
		rm.data = pageSp.list();
		rm.count = pageSp.count();
		return rm;
	}

	/**
	 * 新增订单,不需要认证直接使用
	 */
	// @Path("add")
	@POST
	// @Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Consumes(MediaType.APPLICATION_JSON) // 提交类型
	@Transactional
	public RetMsg add(Orders order) {
		Device dev = Device.findById(order.deviceId);
		LOG.info("order.deviceId:" + order.deviceId);
		order.id=null;
		order.ispId = dev.ispId;// 设置运营商ID
		order.svrId = dev.svrId;// 设置服务商ID
		order.persist();// 提交到数据库
		// order.flush();// 更新到数据库
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		rm.code="0";
		rm.obj = order;

		return rm;
	}

	


	/**
	 * 更新订单支付状态 不需要认证直接使用
	 */
	@Path("pay")
	@POST
	// @Produces(MediaType.APPLICATION_JSON) // 返回类型
	@Consumes(MediaType.APPLICATION_JSON) // 提交类型
	@Transactional
	public RetMsg pay(Orders postOrder 
			/*@PathParam("id") Long id, 
			@PathParam("payStatus") Byte payStatus,
			@QueryParam("payId") String payId,
			@QueryParam("status") Byte status,
			@QueryParam("openId") String openId,
			@QueryParam("surplusCount") Integer surplusCount*/
			) {
		Orders order = Orders.findById(postOrder.id);
		order.status = postOrder.status;
		order.payStatus = postOrder.payStatus;
		order.surplusCount = postOrder.surplusCount;
		order.openId=postOrder.openId;
		// LOG.info(sp.toString());
		order.flush();
		RetMsg rm = (RetMsg) (EntityPool.getEntityObject(RetMsg.class));
		rm.count = 1;
		rm.code = "0";
		rm.obj=null;
		return rm;
	}

}
